﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace client.app
{
    public class Ping : comm.world.BObject
    {
        public int Value { get; private set; }
        public long TimeOffset { get; set; }

        const int PING_INTERVAL = 1000;

        Queue<Action> _callQ = new Queue<Action>();
        bool _firstCheck = true;

        public Ping()
        {
            Timing(PING_INTERVAL, count =>
            {
                if (!_firstCheck)
                {
                    Call((serverT, stT) =>
                    {
                        Value = (int)stT.TotalMilliseconds;
                        var to = stT.Ticks / 2;
                        //Console.WriteLine("校时成功! curr TimeOffset:" + TimeOffset + " new TimeOffset:" + to);
                        TimeOffset = to;
                    });
                }
            });
        }

        public void Check(Action callback)
        {
            _callQ.Enqueue(() =>
            {
                Call((serverT, stT) =>
                {
                    Value = (int)stT.TotalMilliseconds;
                    var to = stT.Ticks / 2;
                    Console.WriteLine("校时成功! curr TimeOffset:" + TimeOffset + " new TimeOffset:" + to);
                    TimeOffset = to;

                    if (callback != null)
                    {
                        callback();
                    }

                    _firstCheck = false;
                });
            });
        }

        void Call(Action<long, TimeSpan> callback)
        {
            var sendTime = DateTime.Now;
            TcpClient.Call(comm.objst.TcpMessageType.ToServerGetServerTime, null, message =>
            {
                var stT = DateTime.Now - sendTime;
                message.TryToObject<long[]>(arr =>
                {
                    callback(arr[0], stT);
                });
            });
        }

        protected override void OnUpdate(comm.TimeStat timeStat)
        {
            while (_callQ.Count > 0)
            {
                _callQ.Dequeue()();
            }
        }
    }
}
